﻿using System;
using System.Net;
using System.Windows.Media.Imaging;

namespace NASA.BeAMartian.Extender
{
    public static class WriteableBitmapExtensions
    {
        /// <summary>
        /// The Pixels array uses Premultiplied ARGB32. This means that if you specify an 
        /// alpha value other than 255 (fully opaque), the other 3 values (red, green, and blue) 
        /// need to be scaled based on the alpha value. This method provides that scaling.
        /// </summary>
        /// <param name="bm">Bitmap</param>
        /// <param name="row">row index into pixel array</param>
        /// <param name="col">column index into pixel array</param>
        /// <param name="alpha">Alpha value 0-255</param>
        /// <param name="r">Red component value 0-255</param>
        /// <param name="g">Red component value 0-255</param>
        /// <param name="b">Red component value 0-255</param>
        public static void SetPixel(this WriteableBitmap bm, int row, int col, byte alpha, byte r, byte g, byte b)
        {
            bm.SetPixel(row * bm.PixelWidth + col, alpha, r, g, b);
        }

        /// <summary>
        /// The Pixels array uses Premultiplied ARGB32. This means that if you specify an 
        /// alpha value other than 255 (fully opaque), the other 3 values (red, green, and blue) 
        /// need to be scaled based on the alpha value. This method provides that scaling.
        /// </summary>
        /// <param name="bm">Bitmap</param>
        /// <param name="idx">Index into pixel array</param>
        /// <param name="alpha">Alpha value 0-255</param>
        /// <param name="r">Red component value 0-255</param>
        /// <param name="g">Red component value 0-255</param>
        /// <param name="b">Red component value 0-255</param>
        public static void SetPixel(this WriteableBitmap bm, int idx, byte alpha, byte r, byte g, byte b)
        {
            byte r1 = (byte)(r * (alpha / 255d));
            byte g1 = (byte)(g * (alpha / 255d));
            byte b1 = (byte)(b * (alpha / 255d));
            bm.Pixels[idx] = (alpha << 24) | (r1 << 16) | (g1 << 8) | b1;
        }
    }
}
